<template>
  <n-config-provider
    :theme="themeConfig.theme ? darkTheme : null"
    class="hz-bg-one"
  >
    <n-el tag="div" class="top_title" @click="toIndexPage">
      <hz-top6
        >下单性别统计</hz-top6
      >
    </n-el>
    <n-layout class="wh100 absolute-box" id="show-box">
      <n-card
        v-for="(item, index) in show_com"
        :key="index"
        :style="{
          margin: '0 auto',
          width: '80%',
          height: '80%',
        }"
        class="absolute-box drag-box"
        :id="item.id"
        hoverable
        :bordered="false"
      >
        <component
          :is="item.component.com"
          :id="item.component.id"
          :ref="setRef"
          :show-title="true"
          :api-path="item.apiOption.apiPath"
          :method="item.apiOption.method"
          :type="item.apiOption.type"
          :params="item.apiOption.params"
        ></component>
      </n-card>
    </n-layout>
  </n-config-provider>
</template>

<script setup lang="ts">
import { darkTheme } from "naive-ui";
// @ts-ignore
import { useThemeConfig, useUserConfig } from "/@bean/GlobalConfig";
import { computed } from "vue";
import { DragData } from "/@bean/GlobalEntity";
import { getHzCom } from "/@utils/GlobalFunction";
import configjs from "/@/pages/bigscreen/config.json";
import { loadEchartsData } from "/@api/hz-bigscreen-api";
import router from "/@/router";


const storesThemeConfig = useThemeConfig();
const useUser = useUserConfig();
// @ts-ignore
const { themeConfig } = storeToRefs(storesThemeConfig);
const { userInfo } = storeToRefs(useUser);

function toIndexPage() {
  router.push({
    name: "MainIndex",
  });
}

// 画布的宽高
const canvas = ref({
  // width: 1920,
  // height: 963,
  width: 1920,
  height: 1125,
});
// 拖拽的偏移量
const dragOffset = ref({
  x: 0,
  y: 0,
  absX: 2,
  absY: 2,
});
// 弹窗消息
let message = useMessage();
// 显示的组件
const show_com = ref([] as DragData[]);

const refs = ref([] as any[]);
const setRef = (e: any) => {
  refs.value.push(e);
};

// 计时器组
const timer = ref([] as any[]);

// 生命周期 页面创建前
onBeforeMount(() => {
  initShowCom();
});

// 生命周期 页面创建后
onMounted(() => {
  // 设置页面整体的缩放比例
  const scale = Math.min(
    window.innerWidth / canvas.value.width,
    window.innerHeight / canvas.value.height
  );
  //@ts-ignore
  document.body.style.zoom = scale.toString();
  // 遍历show_com中的组件 初始化数据 及 创建定时器
  show_com.value.forEach((item: any) => {
    getData(item.component.id);
    // 如果apiPath不为空且params不为true就获取数据
    if (item.apiOption.apiPath !== "" && !item.apiOption.params) {
      getEchartsDataByParams(item.component.id, null);
    }
    // 如果需要携带请求参数，则自定义参数
    if (item.apiOption.params) {
      getDataByParams(item.component.id);
    }
    if (item.component.update) {
      // 如果需要定时更新，就添加定时器
      timer.value.push(
        setInterval(() => {
          getData(item.component.id);
        }, item.component.updateTime)
      );
    }
  });
});

// 监听窗口变化
window.addEventListener("resize", () => {
  // 设置页面整体的缩放比例
  const scale = Math.min(
    window.innerWidth / canvas.value.width,
    window.innerHeight / canvas.value.height
  );
  //@ts-ignore
  document.body.style.zoom = scale.toString();
});

const initShowCom = () => {
  // 获取configjs中的数据
  let config = configjs;

  // 过滤出来对应的图形的id
  config = config.filter((item)=>{return item.id=="box0"})
  // 遍历config
  config.forEach((item: any) => {
    // 将组件添加到show_com中
    show_com.value.push({
      id: item.id,
      position: item.position,
      component: {
        id: item.component.id,
        com: shallowRef(getHzCom(item.component.name)),
        name: item.component.name,
        update: item.component.update,
        updateTime: item.component.updateTime,
      },
      apiOption: {
        apiPath: item.apiOption.apiPath,
        type: item.apiOption.type,
        method: item.apiOption.method,
        params: item.apiOption.params,
      },
    });
  });
};
const getData = async (name: string) => {
  switch (name) {
    case "com0":
      getEchartsDataByParams(name, null);
      break;
    default:
      console.log("[" + name + "]组件没有对应的更新方法");
      return null;
  }
};


const sendMessage = async (msg: Map<string, any>) => {
  // if (msg.get("HZForecast08") != null) {
  //   let category = msg.get("HZForecast08");
  //   if (category == "全部") {
  //     category = null;
  //   }
  //   const echart = refs.value.find((item: any) => item.$props.id === "com8");
  //   echart.refreshCharts(category);
  // }
  if (msg.get("HZForecast05") != null) {
    // 从ref中找到对应的组件
    const echart = refs.value.find((item: any) => item.$props.id === 'com9');
    echart.refreshCharts(msg.get('HZForecast05'))
    // 从ref中找到对应的组件
    const echart2 = refs.value.find((item: any) => item.$props.id === 'com10');
    echart2.refreshChartsByApi({'sid': msg.get('HZForecast05').shop_id})
    const echart3 = refs.value.find((item: any) => item.$props.id === 'com11');
    echart3.refreshChartsByApi({'sid': msg.get('HZForecast05').shop_id})
  }
};
provide("sendMessage", sendMessage);

// 携带参数的通用更新方法
const getEchartsDataByParams = async (name: string, params: any) => {
  // 从ref中找到对应的组件
  const echart = refs.value.find((item: any) => item.$props.id === name);
  // 封装请求参数
  const query = {
    ...params,
  };
  console.log(name);
  
  // 更新图表
  await echart.refreshChartsByApi(query);
};

// 对图表组件自定义请求参数
function getDataByParams(name: string) {
  switch (name) {
    case "com1":
      // 封装你的请求参数
      const params = {
        //样例
        chart_type: "demo",
        name: "张三",
      };
      // 调用更新方法
      getEchartsDataByParams(name, params);
      break;
  }
}

const testGetData = async () => {
  // 等待1秒返回数据
  const s = await new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = {
        title: "柱状图111",
        data: [
          { value: Math.random() * 1000, name: "搜索引擎" },
          { value: Math.random() * 1000, name: "直接访问" },
          { value: Math.random() * 1000, name: "邮件营销" },
          { value: Math.random() * 1000, name: "联盟广告" },
          { value: Math.random() * 1000, name: "视频广告" },
        ],
      };
      resolve(data);
    }, 1000);
  });
  return s;
};
</script>

<style scoped>
.absolute-box {
  position: absolute;
  background: #99999900;
  width: 100%;
  height: 90%;
}
.drag-box {
  z-index: 1;
  background: rgba(255, 255, 255, 0);
}
.css-table {
  top: 700px;
  left: 0;
}

.hz-bg-one {
  background: url("https://students-list.oss-cn-hangzhou.aliyuncs.com/hz-bg/hz-bg-31.png")
    no-repeat;
  background-size: 100% 100%;
  position: relative;
  width: 100%;
  height: 100%;
}

.top_title {
  width: 100%;
  height: 9%;
  zoom: 1;
  cursor: pointer;
}
</style>